﻿using System;
using System.Linq;
using Enyim.Caching;
using System.Web.Mvc;
using SilenthinkContract;
using Web.Areas.Pay.Models;
using SilenthinkContract.Domain;
using System.Collections.Generic;
using SilenthinkCommon.Extension;
using SilenthinkContract.Component;

namespace Web.Areas.Pay.Controllers
{
    public class RechargeController : PayBaseController
    {
        private string resultUrl = "/recharge/result/";
        public RechargeController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient)
            : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        /// <summary>
        /// 充值
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var identity = User.Identity.SkIdentity();
            var model = new RechargeControllerModel.Index();

            var platforms = GetAllPaymentPlatform();
            var tmpEBanks = GetAllPaymentEBank();
            var packages = GetRechargePackages(identity.Id);
            var eBanks = new List<PaymentEBank>();

            foreach (var platform in platforms)
            {
                var p = platform;
                var x = eBanks.Select(o => o.BankId);
                var tmp = tmpEBanks.Where(o => o.PlatformId == p.Id && !x.Contains(o.BankId));
                eBanks.AddRange(tmp.SkipWhile(o => !o.Status));
            }

            model.Account = PaymentService.GetUserAccount(identity.Id);
            model.Packages = packages;
            model.Platforms = platforms;
            model.EBanks = eBanks;
            return View(model);
        }

        /// <summary>
        /// 网银充值
        /// </summary>
        /// <param name="ebank">电子银行Id</param>
        /// <param name="package">充值礼包Id</param>
        /// <returns></returns>
        public ActionResult Debit(int ebank = 0, int package = 0)
        {
            const string url = "/recharge";
            var identity = User.Identity.SkIdentity();
            var model = new RechargeControllerModel.Debit();

            var eBanks = GetAllPaymentEBank();
            var e = eBanks.FirstOrDefault(o => o.Id == ebank);

            if (e != null)
            {
                if (package > 0)
                {
                    var packages = GetRechargePackages(identity.Id);
                    var p = packages.FirstOrDefault(o => o.Id == package);
                    if (p != null)
                    {
                        model.Package = p;
                    }
                    else
                    {
                        return Redirect(url);
                    }
                }
                model.EBank = e;
                model.Account = PaymentService.GetUserAccount(identity.Id);
                return View(model);
            }
            return Redirect(url);
        }

        [HttpPost]
        public ActionResult Debit(int ebank = 0, decimal amount = 0, int package = 0)
        {

            var identity = User.Identity.SkIdentity();
            var eBanks = PaymentService.GetAllPaymentEBank(null, true);
            var e = eBanks.FirstOrDefault(o => o.Id == ebank);

            if (e != null)
            {
                if (package > 0)
                {
                    var packages = GetRechargePackages(identity.Id);
                    var p = packages.FirstOrDefault(o => o.Id == package);
                    if (p != null)
                    {
                        return CreateTrade(e, p.Id, p.OriginalAmount);
                    }
                    return new RedirectResult(resultUrl + 2);
                }
                return CreateTrade(e, 0, amount);
            }
            return new RedirectResult(resultUrl + 1);
        }

        protected ActionResult CreateTrade(PaymentEBank eBank, int packageId, decimal amount)
        {

            var identity = User.Identity.SkIdentity();
            var pay = GetOnlinePay(eBank.PlatformId);

            var dateTime = DateTime.Now;
            var recharge = new UserRecharge();
            var id = dateTime.ToString("ByyyyMMddHHmmssfffffff") + identity.Id;
            if (pay != null)
            {
                recharge.Id = id;
                recharge.UserId = identity.Id;
                recharge.Amount = amount;
                recharge.Paid = 0;
                recharge.Refunded = 0;
                recharge.Category = 0;
                recharge.PackageId = packageId;
                recharge.Gateway = eBank.PaymentBank.Name;
                recharge.Extra = string.Empty;
                recharge.Status = 1;
                recharge.CreatedBy = User.Identity.Name;
                recharge.CreatedOn = dateTime;

                var trade = recharge.ToPayTrade(eBank, Request.UserHostAddress);
                var status = PaymentService.CreateUserRecharge(recharge, trade);
                if (status)
                {
                    try
                    {
                        var t = PaymentService.GetPayTrade(trade.Id);
                        var url = pay.CreatePayUrl(t);
                        return new RedirectResult(url);
                    }
                    catch (Exception)
                    {
                        return new RedirectResult(resultUrl + 5);
                    }
                }
                return new RedirectResult(resultUrl + 4);
            }
            return new RedirectResult(resultUrl + 3);
        }

        [AllowAnonymous]
        public ActionResult Result(int? param)
        {
            return View(param);
        }

        public ActionResult Help()
        {
            return View();
        }

        public ActionResult Credit()
        {
            return new EmptyResult();
        }
    }
}
